package com.xuedakun.xasdk.net.okhttp.upload;

import com.xuedakun.xasdk.XLog;
import com.xuedakun.xasdk.net.okhttp.OkHttpConstants;

import java.io.File;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by xuedakun on 2017/6/8 11:51
 * 上传http部分实现
 *
 * @version : v1.0
 * @project : xasdk
 * @Email : dakun611@Gmail.com
 */

final class UploadHttpHelp {

    private static final String LOG_TAG = "UploadHttpHelp";

    private final OkHttpClient uploadClient;

    public UploadHttpHelp() {
        uploadClient = initUploadClient();
    }

    /**
     * 初始化上传所需的okhttpClient
     * @return
     */
    private OkHttpClient initUploadClient() {
        OkHttpClient okHttpClient = new OkHttpClient();
        return okHttpClient;
    }

    /**
     * 生成post的Request(以表单的形式，可上传文件)
     * 监听进度
     * @param url
     * @param headers
     * @param params
     * @return
     */
    public Response doRequest(String url, Map<String, String> headers, Map<String, Object> params, String fileKey, File file, IUploadListener listener) {
        try {
            Request.Builder builder = new Request.Builder();
            for (String key : headers.keySet()) {
                builder.header(key, headers.get(key));
            }
            RequestBody requestBody = new UploadRequestBody(listener, getRequestBody(params, fileKey, file));
            Call call = uploadClient.newCall(builder.url(url).post(requestBody).build());
            return call.execute();
        } catch (Exception e) {
            XLog.e(LOG_TAG, "DO POST WITH FILE REQUEST ERROR!");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 生成表单的RequestBody，用于post上传数据
     *
     * @param params
     * @return
     */
    private RequestBody getRequestBody(Map<String, Object> params, String fileKey, File file) {
        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);

        XLog.e(LOG_TAG, "fileName:" + file.getName());
        builder.addFormDataPart(fileKey, file.getName(), RequestBody.create(OkHttpConstants.FILE, file));

        for (String key : params.keySet()) {
            if(params.get(key) == null){
                continue;
            }
            builder.addFormDataPart(key, null, RequestBody.create(OkHttpConstants.FORM, params.get(key).toString()));
            XLog.e(LOG_TAG, "upload argument:" + key + "----value:" + params.get(key));
        }
        RequestBody requestBody = builder.build();
        return requestBody;
    }
}
